1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- // Package server is an adaptation of the basic Auth demo by Alex Edwards
- // on https://www.alexedwards.net/blog/basic-authentication-in-go
- // where it is published under an MIT license.
- package server
- import (
- "errors"
- "fmt"
- "net/http"
- "os"
- )
- type Auth struct {
- Username, Password string
- }
- type TLS struct {
- Cert, Key string
- }
- type Application struct {
- Auth
- TLS
- }
- func (app *Application) UnprotectedHandler(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintln(w, "this is the unprotected handler")
- }
- func (app *Application) ProtectedHandler(w http.ResponseWriter, r *http.Request) {
- fmt.Fprintln(w, "this is the protected handler")
- }
- func New(user, pass, cert, ckey string) (*Application, error) {
- if user == "" {
- return nil, errors.New("invalid username: may not be empty")
- }
- if pass == "" {
- return nil, errors.New("invalid password: may not be empty")
- }
- if cert == "" {
- return nil, errors.New("invalid certificate path: may not be empty")
- }
- if _, err := os.ReadFile(cert); err != nil {
- return nil, fmt.Errorf("cannot read certificate file %s: %w", cert, err)
- }
- if ckey == "" {
- return nil, errors.New("invalid certificate key path: may not be empty")
- }
- if _, err := os.ReadFile(ckey); err != nil {
- return nil, fmt.Errorf("cannot read certificate key file %s: %w", cert, err)
- }
- app := &Application{
- Auth{Username: user, Password: pass},
- TLS{Cert: cert, Key: ckey},
- }
- return app, nil
- }
|