-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
50 lines (44 loc) · 1.01 KB
/
main.go
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
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"github.com/julienschmidt/httprouter"
)
type book struct {
Name string
Id int
Desc string
}
var books = map[int]book{
1: {Name: "哈利波特", Id: 1, Desc: "小说"},
2: {Name: "时间简史", Id: 2, Desc: "科普读物"},
3: {Name: "Go程序设计语言", Id: 3, Desc: "程序设计"},
}
func bookHandleFunc(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
fmt.Println(r.Proto)
id := p.ByName("id")
bookId, err := strconv.Atoi(id)
if err != nil {
log.Fatal(err)
}
book, ok := books[bookId]
if !ok {
fmt.Fprintf(rw, "not find the book.")
} else {
fmt.Fprintf(rw, "Book details:\n")
fmt.Fprintf(rw, "name: %s\n", book.Name)
fmt.Fprintf(rw, "id: %d\n", book.Id)
fmt.Fprintf(rw, "description:%s\n", book.Desc)
}
}
func main() {
router := httprouter.New()
router.GET("/book/:id", bookHandleFunc)
server := http.Server{
Addr: ":8080",
Handler: router,
}
server.ListenAndServeTLS("../ssl/cert.pem", "../ssl/key.pem")
}