~miconoco/sayhello

635ba6a95c9c051c403b383cd6d9aaf5ade10ea6 — Christoph Polcin 8 months ago 851b8bc master
Add cmd/sayhello
2 files changed, 50 insertions(+), 0 deletions(-)

A cmd/sayhello/main.go
A go.mod
A cmd/sayhello/main.go => cmd/sayhello/main.go +47 -0
@@ 0,0 1,47 @@
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
)

func sayhello(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.Error(w, "404 Not Found.", http.StatusNotFound)
		return
	}
	if r.Method == http.MethodPost {
		if err := r.ParseForm(); err != nil {
			goto BADREQ
		}
		name := r.FormValue("name")
		address := r.FormValue("address")
		fmt.Fprintf(w, "Name = %s\n", name)
		fmt.Fprintf(w, "Address = %s\n", address)
		return
	}
BADREQ:
	http.Error(w, "400 Bad Request ", http.StatusBadRequest)
}

func main() {
	var listen string
	var action string

	flag.StringVar(&listen, "l", "localhost:8081", "Listen on localhost:8081")
	flag.StringVar(&action, "a", "/", "Action '/'")

	flag.Usage = func() {
		fmt.Printf("usage: sayhello [-l localhost:8080] [-a /]\n")
	}

	flag.Parse()

	mux := http.NewServeMux()
	mux.HandleFunc(action, sayhello)
	if err := http.ListenAndServe(listen, mux); err != nil {
		log.Fatal(err)
	}
}

A go.mod => go.mod +3 -0
@@ 0,0 1,3 @@
module git.sr.ht/~miconoco/sayhello

go 1.16