-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
97 lines (73 loc) · 1.71 KB
/
main.go
File metadata and controls
97 lines (73 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
var jsonPath string
func jsonHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method is not supported", http.StatusNotFound)
return
}
jsonFile, err := os.Open(jsonPath)
byteValue, _ := ioutil.ReadAll(jsonFile)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(byteValue)
if err != nil {
return
}
defer jsonFile.Close()
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/hello" {
http.Error(w, "404 not found", http.StatusNotFound)
return
}
if r.Method != http.MethodGet {
http.Error(w, "Method is not supported", http.StatusNotFound)
return
}
_, err := fmt.Fprintf(w, "Hello")
if err != nil {
return
}
}
func formHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
_, err := fmt.Fprintf(w, "Error %v", err)
if err != nil {
return
}
}
_, err := fmt.Fprintf(w, "Post Request succesfull")
if err != nil {
return
}
name := r.FormValue("name")
_, err = fmt.Fprintf(w, "Hello %s\n", name)
if err != nil {
return
}
}
func main() {
fileServer := http.FileServer(http.Dir("./static"))
argsWithoutProg := os.Args[1:]
fmt.Println(argsWithoutProg[0])
jsonPath = argsWithoutProg[0]
http.Handle("/", fileServer)
http.HandleFunc("/form", formHandler)
http.HandleFunc("/hello", helloHandler)
http.HandleFunc("/json", jsonHandler)
http.HandleFunc("/json/", jsonHandler)
fmt.Printf("Server started at port 8080")
//if err != nil {
// log.Fatal("ListenAndServe: ", err)
//}
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}