all repos — flounder @ 0369b3b9d007500f8354cb920a66d30fc49c8e94

A small site builder for the Gemini protocol

http.go (view raw)

  1package main
  2
  3import (
  4	"bytes"
  5	"database/sql"
  6	"fmt"
  7	gmi "git.sr.ht/~adnano/go-gemini"
  8	"github.com/gorilla/handlers"
  9	"github.com/gorilla/sessions"
 10	_ "github.com/mattn/go-sqlite3"
 11	"golang.org/x/crypto/bcrypt"
 12	"html/template"
 13	"io"
 14	"io/ioutil"
 15	"log"
 16	"mime"
 17	"net/http"
 18	"os"
 19	"path"
 20	"path/filepath"
 21	"strings"
 22	"time"
 23)
 24
 25var t *template.Template
 26var DB *sql.DB
 27var SessionStore *sessions.CookieStore
 28
 29func renderDefaultError(w http.ResponseWriter, statusCode int) {
 30	errorMsg := http.StatusText(statusCode)
 31	renderError(w, errorMsg, statusCode)
 32}
 33
 34func renderError(w http.ResponseWriter, errorMsg string, statusCode int) {
 35	data := struct {
 36		PageTitle  string
 37		StatusCode int
 38		ErrorMsg   string
 39	}{"Error!", statusCode, errorMsg}
 40	err := t.ExecuteTemplate(w, "error.html", data)
 41	if err != nil { // Shouldn't happen probably
 42		http.Error(w, errorMsg, statusCode)
 43	}
 44}
 45
 46func rootHandler(w http.ResponseWriter, r *http.Request) {
 47	// serve everything inside static directory
 48	if r.URL.Path != "/" {
 49		fileName := path.Join(c.TemplatesDirectory, "static", filepath.Clean(r.URL.Path))
 50		_, err := os.Stat(fileName)
 51		if err != nil {
 52			renderDefaultError(w, http.StatusNotFound)
 53			return
 54		}
 55		http.ServeFile(w, r, fileName) // TODO better error handling
 56		return
 57	}
 58
 59	user := newGetAuthUser(r)
 60	indexFiles, err := getIndexFiles(user.IsAdmin)
 61	if err != nil {
 62		panic(err)
 63	}
 64	allUsers, err := getActiveUserNames()
 65	if err != nil {
 66		panic(err)
 67	}
 68	data := struct {
 69		Host      string
 70		PageTitle string
 71		Files     []*File
 72		Users     []string
 73		AuthUser  AuthUser
 74	}{c.Host, c.SiteTitle, indexFiles, allUsers, user}
 75	err = t.ExecuteTemplate(w, "index.html", data)
 76	if err != nil {
 77		panic(err)
 78	}
 79}
 80
 81func feedHandler(w http.ResponseWriter, r *http.Request) {
 82	user := newGetAuthUser(r)
 83	feedEntries, feeds, err := getAllGemfeedEntries()
 84	if err != nil {
 85		panic(err)
 86	}
 87	data := struct {
 88		Host        string
 89		PageTitle   string
 90		FeedEntries []*FeedEntry
 91		Feeds       []*Gemfeed
 92		AuthUser    AuthUser
 93	}{c.Host, c.SiteTitle, feedEntries, feeds, user}
 94	err = t.ExecuteTemplate(w, "feed.html", data)
 95	if err != nil {
 96		panic(err)
 97	}
 98}
 99
100func editFileHandler(w http.ResponseWriter, r *http.Request) {
101	user := newGetAuthUser(r)
102	if !user.LoggedIn {
103		renderDefaultError(w, http.StatusForbidden)
104		return
105	}
106	fileName := filepath.Clean(r.URL.Path[len("/edit/"):])
107	isText := strings.HasPrefix(mime.TypeByExtension(path.Ext(fileName)), "text")
108	filePath := path.Join(c.FilesDirectory, user.Username, fileName)
109
110	if r.Method == "GET" {
111		err := checkIfValidFile(filePath, nil)
112		if err != nil {
113			log.Println(err)
114			renderError(w, err.Error(), http.StatusBadRequest)
115			return
116		}
117		// Create directories if dne
118		f, err := os.OpenFile(filePath, os.O_RDONLY, 0644)
119		var fileBytes []byte
120		if os.IsNotExist(err) || !isText {
121			fileBytes = []byte{}
122			err = nil
123		} else {
124			defer f.Close()
125			fileBytes, err = ioutil.ReadAll(f)
126		}
127		if err != nil {
128			panic(err)
129		}
130		data := struct {
131			FileName  string
132			FileText  string
133			PageTitle string
134			AuthUser  AuthUser
135			Host      string
136			IsText    bool
137		}{fileName, string(fileBytes), c.SiteTitle, user, c.Host, isText}
138		err = t.ExecuteTemplate(w, "edit_file.html", data)
139		if err != nil {
140			panic(err)
141		}
142	} else if r.Method == "POST" {
143		// get post body
144		r.ParseForm()
145		fileText := r.Form.Get("file_text")
146		// Web form by default gives us CR LF newlines.
147		// Unix files use just LF
148		fileText = strings.ReplaceAll(fileText, "\r\n", "\n")
149		fileBytes := []byte(fileText)
150		err := checkIfValidFile(filePath, fileBytes)
151		if err != nil {
152			log.Println(err)
153			renderError(w, err.Error(), http.StatusBadRequest)
154			return
155		}
156		// create directories if dne
157		os.MkdirAll(path.Dir(filePath), os.ModePerm)
158		if userHasSpace(user.Username, len(fileBytes)) {
159			if isText { // Cant edit binary files here
160				err = ioutil.WriteFile(filePath, fileBytes, 0644)
161			}
162		} else {
163			renderError(w, fmt.Sprintf("Bad Request: Out of file space. Max space: %d.", c.MaxUserBytes), http.StatusBadRequest)
164			return
165		}
166		if err != nil {
167			panic(err)
168		}
169		newName := filepath.Clean(r.Form.Get("rename"))
170		err = checkIfValidFile(newName, fileBytes)
171		if err != nil {
172			log.Println(err)
173			renderError(w, err.Error(), http.StatusBadRequest)
174			return
175		}
176		if newName != fileName {
177			newPath := path.Join(c.FilesDirectory, user.Username, newName)
178			os.MkdirAll(path.Dir(newPath), os.ModePerm)
179			os.Rename(filePath, newPath)
180			fileName = newName
181		}
182		http.Redirect(w, r, path.Join("/edit", fileName), http.StatusSeeOther)
183	}
184}
185
186func uploadFilesHandler(w http.ResponseWriter, r *http.Request) {
187	if r.Method == "POST" {
188		user := newGetAuthUser(r)
189		if !user.LoggedIn {
190			renderDefaultError(w, http.StatusForbidden)
191			return
192		}
193		r.ParseMultipartForm(10 << 6) // why does this not work
194		file, fileHeader, err := r.FormFile("file")
195		fileName := filepath.Clean(fileHeader.Filename)
196		defer file.Close()
197		if err != nil {
198			log.Println(err)
199			renderError(w, err.Error(), http.StatusBadRequest)
200			return
201		}
202		dest, _ := ioutil.ReadAll(file)
203		err = checkIfValidFile(fileName, dest)
204		if err != nil {
205			log.Println(err)
206			renderError(w, err.Error(), http.StatusBadRequest)
207			return
208		}
209		destPath := path.Join(c.FilesDirectory, user.Username, fileName)
210
211		f, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE, 0644)
212		if err != nil {
213			panic(err)
214		}
215		defer f.Close()
216		if userHasSpace(user.Username, c.MaxFileBytes) { // Not quite right
217			io.Copy(f, bytes.NewReader(dest))
218		} else {
219			renderError(w, fmt.Sprintf("Bad Request: Out of file space. Max space: %d.", c.MaxUserBytes), http.StatusBadRequest)
220			return
221		}
222	}
223	http.Redirect(w, r, "/my_site", http.StatusSeeOther)
224}
225
226type AuthUser struct {
227	LoggedIn          bool
228	Username          string
229	IsAdmin           bool
230	ImpersonatingUser string // used if impersonating
231}
232
233func newGetAuthUser(r *http.Request) AuthUser {
234	session, _ := SessionStore.Get(r, "cookie-session")
235	user, ok := session.Values["auth_user"].(string)
236	impers, _ := session.Values["impersonating_user"].(string)
237	isAdmin, _ := session.Values["admin"].(bool)
238	return AuthUser{
239		LoggedIn:          ok,
240		Username:          user,
241		IsAdmin:           isAdmin,
242		ImpersonatingUser: impers,
243	}
244}
245
246func mySiteHandler(w http.ResponseWriter, r *http.Request) {
247	user := newGetAuthUser(r)
248	if !user.LoggedIn {
249		renderDefaultError(w, http.StatusForbidden)
250		return
251	}
252	// check auth
253	userFolder := getUserDirectory(user.Username)
254	files, _ := getMyFilesRecursive(userFolder, user.Username)
255	data := struct {
256		Host      string
257		PageTitle string
258		Files     []*File
259		AuthUser  AuthUser
260	}{c.Host, c.SiteTitle, files, user}
261	_ = t.ExecuteTemplate(w, "my_site.html", data)
262}
263
264func myAccountHandler(w http.ResponseWriter, r *http.Request) {
265	user := newGetAuthUser(r)
266	authUser := user.Username
267	if !user.LoggedIn {
268		renderDefaultError(w, http.StatusForbidden)
269		return
270	}
271	me, _ := getUserByName(user.Username)
272	type pageData struct {
273		PageTitle string
274		AuthUser  AuthUser
275		Email     string
276		Errors    []string
277	}
278	data := pageData{"My Account", user, me.Email, nil}
279
280	if r.Method == "GET" {
281		err := t.ExecuteTemplate(w, "me.html", data)
282		if err != nil {
283			panic(err)
284		}
285	} else if r.Method == "POST" {
286		r.ParseForm()
287		newUsername := r.Form.Get("username")
288		errors := []string{}
289		newEmail := r.Form.Get("email")
290		newUsername = strings.ToLower(newUsername)
291		var err error
292		if newEmail != me.Email {
293			_, err = DB.Exec("update user set email = ? where username = ?", newEmail, me.Email)
294			if err != nil {
295				// TODO better error not sql
296				errors = append(errors, err.Error())
297			} else {
298				log.Printf("Changed email for %s from %s to %s", authUser, me.Email, newEmail)
299			}
300		}
301		if newUsername != authUser {
302			// Rename User
303			err = renameUser(authUser, newUsername)
304			if err != nil {
305				log.Println(err)
306				errors = append(errors, "Could not rename user")
307			} else {
308				session, _ := SessionStore.Get(r, "cookie-session")
309				session.Values["auth_user"] = newUsername
310				session.Save(r, w)
311			}
312		}
313		// reset auth
314		user = newGetAuthUser(r)
315		data.Errors = errors
316		data.AuthUser = user
317		data.Email = newEmail
318		_ = t.ExecuteTemplate(w, "me.html", data)
319	}
320}
321
322func archiveHandler(w http.ResponseWriter, r *http.Request) {
323	authUser := newGetAuthUser(r)
324	if !authUser.LoggedIn {
325		renderDefaultError(w, http.StatusForbidden)
326		return
327	}
328	if r.Method == "GET" {
329		userFolder := getUserDirectory(authUser.Username)
330		err := zipit(userFolder, w)
331		if err != nil {
332			panic(err)
333		}
334
335	}
336}
337func loginHandler(w http.ResponseWriter, r *http.Request) {
338	if r.Method == "GET" {
339		// show page
340		data := struct {
341			Error     string
342			PageTitle string
343		}{"", "Login"}
344		err := t.ExecuteTemplate(w, "login.html", data)
345		if err != nil {
346			panic(err)
347		}
348	} else if r.Method == "POST" {
349		r.ParseForm()
350		name := r.Form.Get("username")
351		password := r.Form.Get("password")
352		row := DB.QueryRow("SELECT username, password_hash, active, admin FROM user where username = $1 OR email = $1", name)
353		var db_password []byte
354		var username string
355		var active bool
356		var isAdmin bool
357		err := row.Scan(&username, &db_password, &active, &isAdmin)
358		if err != nil {
359			panic(err)
360		}
361		if db_password != nil && !active {
362			data := struct {
363				Error     string
364				PageTitle string
365			}{"Your account is not active yet. Pending admin approval", c.SiteTitle}
366			t.ExecuteTemplate(w, "login.html", data)
367			return
368		}
369		if bcrypt.CompareHashAndPassword(db_password, []byte(password)) == nil {
370			log.Println("logged in")
371			session, _ := SessionStore.Get(r, "cookie-session")
372			session.Values["auth_user"] = username
373			session.Values["admin"] = isAdmin
374			session.Save(r, w)
375			http.Redirect(w, r, "/my_site", http.StatusSeeOther)
376		} else {
377			data := struct {
378				Error     string
379				PageTitle string
380			}{"Invalid login or password", c.SiteTitle}
381			err := t.ExecuteTemplate(w, "login.html", data)
382			if err != nil {
383				panic(err)
384			}
385		}
386	}
387}
388
389func logoutHandler(w http.ResponseWriter, r *http.Request) {
390	session, _ := SessionStore.Get(r, "cookie-session")
391	impers, ok := session.Values["impersonating_user"].(string)
392	if ok {
393		session.Values["auth_user"] = impers
394		session.Values["impersonating_user"] = nil // TODO expire this automatically
395		// session.Values["admin"] = nil // TODO fix admin
396	} else {
397		session.Options.MaxAge = -1
398	}
399	session.Save(r, w)
400	http.Redirect(w, r, "/", http.StatusSeeOther)
401}
402
403const ok = "-0123456789abcdefghijklmnopqrstuvwxyz"
404
405func isOkUsername(s string) error {
406	if len(s) < 1 {
407		return fmt.Errorf("Username is too short")
408	}
409	if len(s) > 32 {
410		return fmt.Errorf("Username is too long. 32 char max.")
411	}
412	for _, char := range s {
413		if !strings.Contains(ok, strings.ToLower(string(char))) {
414			return fmt.Errorf("Username contains invalid characters. Valid characters include lowercase letters, numbers, and hyphens.")
415		}
416	}
417	return nil
418}
419func registerHandler(w http.ResponseWriter, r *http.Request) {
420	if r.Method == "GET" {
421		data := struct {
422			Host      string
423			Errors    []string
424			PageTitle string
425		}{c.Host, nil, "Register"}
426		err := t.ExecuteTemplate(w, "register.html", data)
427		if err != nil {
428			panic(err)
429		}
430	} else if r.Method == "POST" {
431		r.ParseForm()
432		email := r.Form.Get("email")
433		password := r.Form.Get("password")
434		errors := []string{}
435		if r.Form.Get("password") != r.Form.Get("password2") {
436			errors = append(errors, "Passwords don't match")
437		}
438		if len(password) < 6 {
439			errors = append(errors, "Password is too short")
440		}
441		username := strings.ToLower(r.Form.Get("username"))
442		err := isOkUsername(username)
443		if err != nil {
444			errors = append(errors, err.Error())
445		}
446		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // TODO handle error
447		if err != nil {
448			panic(err)
449		}
450		reference := r.Form.Get("reference")
451		if len(errors) == 0 {
452			_, err = DB.Exec("insert into user (username, email, password_hash, reference) values ($1, $2, $3, $4)", username, email, string(hashedPassword), reference)
453			if err != nil {
454				errors = append(errors, "Username or email is already used")
455			}
456		}
457		if len(errors) > 0 {
458			data := struct {
459				Host      string
460				Errors    []string
461				PageTitle string
462			}{c.Host, errors, "Register"}
463			t.ExecuteTemplate(w, "register.html", data)
464		} else {
465			data := struct {
466				Host      string
467				Message   string
468				PageTitle string
469			}{c.Host, "Registration complete! The server admin will approve your request before you can log in.", "Registration Complete"}
470			t.ExecuteTemplate(w, "message.html", data)
471		}
472	}
473}
474
475func deleteFileHandler(w http.ResponseWriter, r *http.Request) {
476	user := newGetAuthUser(r)
477	if !user.LoggedIn {
478		renderDefaultError(w, http.StatusForbidden)
479		return
480	}
481	filePath := safeGetFilePath(user.Username, r.URL.Path[len("/delete/"):])
482	if r.Method == "POST" {
483		os.Remove(filePath) // TODO handle error
484	}
485	http.Redirect(w, r, "/my_site", http.StatusSeeOther)
486}
487
488func adminHandler(w http.ResponseWriter, r *http.Request) {
489	user := newGetAuthUser(r)
490	if !user.IsAdmin {
491		renderDefaultError(w, http.StatusForbidden)
492		return
493	}
494	allUsers, err := getUsers()
495	if err != nil {
496		log.Println(err)
497		renderDefaultError(w, http.StatusInternalServerError)
498		return
499	}
500	data := struct {
501		Users     []User
502		AuthUser  AuthUser
503		PageTitle string
504		Host      string
505	}{allUsers, user, "Admin", c.Host}
506	err = t.ExecuteTemplate(w, "admin.html", data)
507	if err != nil {
508		panic(err)
509	}
510}
511
512func getFavicon(user string) string {
513	faviconPath := path.Join(c.FilesDirectory, filepath.Clean(user), "favicon.txt")
514	content, err := ioutil.ReadFile(faviconPath)
515	if err != nil {
516		return ""
517	}
518	strcontent := []rune(string(content))
519	if len(strcontent) > 0 {
520		return string(strcontent[0])
521	}
522	return ""
523}
524
525// Server a user's file
526func userFile(w http.ResponseWriter, r *http.Request) {
527	userName := filepath.Clean(strings.Split(r.Host, ".")[0]) // Clean probably unnecessary
528	p := filepath.Clean(r.URL.Path)
529	var isDir bool
530	fileName := path.Join(c.FilesDirectory, userName, p)
531	stat, err := os.Stat(fileName)
532	if stat != nil {
533		isDir = stat.IsDir()
534	}
535	if p == "/" || isDir {
536		fileName = path.Join(fileName, "index.gmi")
537	}
538
539	if strings.HasPrefix(p, "/.hidden") {
540		renderDefaultError(w, http.StatusForbidden)
541		return
542	}
543	if r.URL.Path == "/style.css" {
544		http.ServeFile(w, r, path.Join(c.TemplatesDirectory, "static/style.css"))
545		return
546	}
547
548	_, err = os.Stat(fileName)
549	if os.IsNotExist(err) {
550		renderDefaultError(w, http.StatusNotFound)
551		return
552	}
553
554	// Dumb content negotiation
555	_, raw := r.URL.Query()["raw"]
556	acceptsGemini := strings.Contains(r.Header.Get("Accept"), "text/gemini")
557	if !raw && !acceptsGemini && isGemini(fileName) {
558		file, _ := os.Open(fileName)
559		htmlString := textToHTML(gmi.ParseText(file))
560		favicon := getFavicon(userName)
561		hostname := strings.Split(r.Host, ":")[0]
562		URI := hostname + r.URL.String()
563		data := struct {
564			SiteBody  template.HTML
565			Favicon   string
566			PageTitle string
567			URI       string
568		}{template.HTML(htmlString), favicon, userName + p, URI}
569		t.ExecuteTemplate(w, "user_page.html", data)
570	} else {
571		http.ServeFile(w, r, fileName)
572	}
573}
574
575func deleteAccountHandler(w http.ResponseWriter, r *http.Request) {
576	user := newGetAuthUser(r)
577	if r.Method == "POST" {
578		r.ParseForm()
579		validate := r.Form.Get("validate-delete")
580		if validate == user.Username {
581			err := deleteUser(user.Username)
582			if err != nil {
583				log.Println(err)
584				renderDefaultError(w, http.StatusInternalServerError)
585				return
586			}
587			logoutHandler(w, r)
588		} else {
589			http.Redirect(w, r, "/me", http.StatusSeeOther)
590		}
591	}
592}
593
594func resetPasswordHandler(w http.ResponseWriter, r *http.Request) {
595	user := newGetAuthUser(r)
596	data := struct {
597		PageTitle string
598		AuthUser  AuthUser
599		Error     string
600	}{"Reset Password", user, ""}
601	if r.Method == "GET" {
602		err := t.ExecuteTemplate(w, "reset_pass.html", data)
603		if err != nil {
604			panic(err)
605		}
606	} else if r.Method == "POST" {
607		r.ParseForm()
608		enteredCurrPass := r.Form.Get("password")
609		password1 := r.Form.Get("new_password1")
610		password2 := r.Form.Get("new_password2")
611		if password1 != password2 {
612			data.Error = "New passwords do not match"
613		} else if len(password1) < 6 {
614			data.Error = "Password is too short"
615		} else {
616			err := checkAuth(user.Username, enteredCurrPass)
617			if err == nil {
618				hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password1), 8)
619				if err != nil {
620					panic(err)
621				}
622				_, err = DB.Exec("update user set password_hash = ? where username = ?", hashedPassword, user.Username)
623				if err != nil {
624					panic(err)
625				}
626				log.Printf("User %s reset password", user.Username)
627				http.Redirect(w, r, "/me", http.StatusSeeOther)
628				return
629			} else {
630				data.Error = "That's not your current password"
631			}
632		}
633		err := t.ExecuteTemplate(w, "reset_pass.html", data)
634		if err != nil {
635			panic(err)
636		}
637	}
638}
639
640func adminUserHandler(w http.ResponseWriter, r *http.Request) {
641	user := newGetAuthUser(r)
642	if r.Method == "POST" {
643		if !user.IsAdmin {
644			renderDefaultError(w, http.StatusForbidden)
645			return
646		}
647		components := strings.Split(r.URL.Path, "/")
648		if len(components) < 5 {
649			renderError(w, "Invalid action", http.StatusBadRequest)
650			return
651		}
652		userName := components[3]
653		action := components[4]
654		var err error
655		if action == "activate" {
656			err = activateUser(userName)
657		} else if action == "impersonate" {
658			if user.ImpersonatingUser != "" {
659				// Don't allow nested impersonation
660				renderError(w, "Cannot nest impersonation, log out from impersonated user first.", 400)
661				return
662			}
663			session, _ := SessionStore.Get(r, "cookie-session")
664			session.Values["auth_user"] = userName
665			session.Values["impersonating_user"] = user.Username
666			session.Save(r, w)
667			log.Printf("User %s impersonated %s", user.Username, userName)
668			http.Redirect(w, r, "/", http.StatusSeeOther)
669			return
670		}
671		if err != nil {
672			log.Println(err)
673			renderDefaultError(w, http.StatusInternalServerError)
674			return
675		}
676		http.Redirect(w, r, "/admin", http.StatusSeeOther)
677	}
678}
679
680func runHTTPServer() {
681	log.Printf("Running http server with hostname %s on port %d. TLS enabled: %t", c.Host, c.HttpPort, c.HttpsEnabled)
682	var err error
683	t, err = template.ParseGlob(path.Join(c.TemplatesDirectory, "*.html"))
684	if err != nil {
685		log.Fatal(err)
686	}
687	serveMux := http.NewServeMux()
688
689	s := strings.SplitN(c.Host, ":", 2)
690	hostname := s[0]
691	port := c.HttpPort
692
693	serveMux.HandleFunc(hostname+"/", rootHandler)
694	serveMux.HandleFunc(hostname+"/feed", feedHandler)
695	serveMux.HandleFunc(hostname+"/my_site", mySiteHandler)
696	serveMux.HandleFunc(hostname+"/me", myAccountHandler)
697	serveMux.HandleFunc(hostname+"/my_site/flounder-archive.zip", archiveHandler)
698	serveMux.HandleFunc(hostname+"/admin", adminHandler)
699	serveMux.HandleFunc(hostname+"/edit/", editFileHandler)
700	serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler)
701	serveMux.Handle(hostname+"/login", limit(http.HandlerFunc(loginHandler)))
702	serveMux.Handle(hostname+"/register", limit(http.HandlerFunc(registerHandler)))
703	serveMux.HandleFunc(hostname+"/logout", logoutHandler)
704	serveMux.HandleFunc(hostname+"/delete/", deleteFileHandler)
705	serveMux.HandleFunc(hostname+"/delete-account", deleteAccountHandler)
706	serveMux.HandleFunc(hostname+"/reset-password", resetPasswordHandler)
707
708	// admin commands
709	serveMux.HandleFunc(hostname+"/admin/user/", adminUserHandler)
710	// TODO authentication
711	serveMux.HandleFunc(hostname+"/webdav/", webdavHandler)
712
713	wrapped := (handlers.LoggingHandler(log.Writer(), handlers.RecoveryHandler()(serveMux)))
714
715	// handle user files based on subdomain
716	serveMux.HandleFunc("/", userFile)
717	// login+register functions
718	srv := &http.Server{
719		ReadTimeout:  5 * time.Second,
720		WriteTimeout: 10 * time.Second,
721		IdleTimeout:  120 * time.Second,
722		Addr:         fmt.Sprintf(":%d", port),
723		// TLSConfig:    tlsConfig,
724		Handler: wrapped,
725	}
726	if c.HttpsEnabled {
727		log.Fatal(srv.ListenAndServeTLS(c.TLSCertFile, c.TLSKeyFile))
728	} else {
729		log.Fatal(srv.ListenAndServe())
730	}
731}