美文网首页
Go小项目-新闻网站

Go小项目-新闻网站

作者: c4a1d989518e | 来源:发表于2018-03-14 16:42 被阅读117次

    项目描述

    用go实现后端,来搭建一个网站,展示不同的故事,故事下面有超链接,可以跳转到其他网页。

    实验效果

    运行结果

    一个基础的go后端

    这个代码有问题,没有运行起来,但是其中的代码还是很基础的,还是有很大的参考意义的。

    package main
    
    import (
        "fmt"
        "net/http"
    
        "github.com/gophercises/urlshort"
    )
    
    func main() {
        mux := defaultMux()
    
        // Build the MapHandler using the mux as the fallback
        pathsToUrls := map[string]string{
            "/urlshort-godoc": "https://godoc.org/github.com/gophercises/urlshort",
            "/yaml-godoc":     "https://godoc.org/gopkg.in/yaml.v2",
        }
        mapHandler := urlshort.MapHandler(pathsToUrls, mux)
    
        // Build the YAMLHandler using the mapHandler as the
        // fallback
        yaml := `
    - path: /urlshort
      url: https://github.com/gophercises/urlshort
    - path: /urlshort-final
      url: https://github.com/gophercises/urlshort/tree/solution
    `
        yamlHandler, err := urlshort.YAMLHandler([]byte(yaml), mapHandler)
        if err != nil {
            panic(err)
            return
        }
        fmt.Println("Starting the server on :8080")
        http.ListenAndServe(":8080", yamlHandler)
    }
    
    func defaultMux() *http.ServeMux {
        mux := http.NewServeMux()
        mux.HandleFunc("/", hello)
        return mux
    }
    
    func hello(w http.ResponseWriter, r *http.Request) {
        
        fmt.Fprintln(w, "Hello, world!")
    }
    
    

    代码部分

    网页展示的故事,和链接,标题是来自于一个json文件。


    json文件

    main.go文件的代码为

    package main
    
    import (
        "flag"
        "fmt"
        "html/template"
        "log"
        "net/http"
        "os"
        "strings"
    
        "github.com/gophercises/cyoa"
    )
    
    func main() {
        // Create flags for our optional variables
        port := flag.Int("port", 3000, "the port to start the CYOA web application on")
        filename := flag.String("file", "gopher.json", "the JSON file with the CYOA story")
        flag.Parse()
        fmt.Printf("Using the story in %s.\n", *filename)
    
        // Open the JSON file and parse the story in it.
        f, err := os.Open(*filename)
        if err != nil {
            panic(err)
        }
        story, err := cyoa.JsonStory(f)
        if err != nil {
            panic(err)
        }
    
        // Create our custom CYOA story handler
        tpl := template.Must(template.New("").Parse(storyTmpl))
        h := cyoa.NewHandler(story,
            cyoa.WithTemplate(tpl),
            cyoa.WithPathFunc(pathFn),
        )
        // Create a ServeMux to route our requests
        mux := http.NewServeMux()
        // This story handler is using a custom function and template
        // Because we use /story/ (trailing slash) all web requests
        // whose path has the /story/ prefix will be routed here.
        mux.Handle("/story/", h)
        // This story handler is using the default functions and templates
        // Because we use / (base path) all incoming requests not
        // mapped elsewhere will be sent here.
        mux.Handle("/", cyoa.NewHandler(story))
        // Start the server using our ServeMux
        fmt.Printf("Starting the server on port: %d\n", *port)
        log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), mux))
    }
    
    // Updated chapter parsing function. Technically you don't
    // *have* to get the story from the path (it could be a
    // header or anything else) but I'm not going to rename this
    // since "path" is what we used in the videos.
    func pathFn(r *http.Request) string {
        path := strings.TrimSpace(r.URL.Path)
        if path == "/story" || path == "/story/" {
            path = "/story/intro"
        }
        return path[len("/story/"):]
    }
    
    // Slightly altered tempalte to show how this feature works
    var storyTmpl = `
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Choose Your Own Adventure</title>
      </head>
      <body>
        <section class="page">
          <h1>{{.Title}}</h1>
          {{range .Paragraphs}}
            <p>{{.}}</p>
          {{end}}
          <ul>
          {{range .Options}}
            <li><a href="/story/{{.Chapter}}">{{.Text}}</a></li>
          {{end}}
          </ul>
        </section>
        <style>
          body {
            font-family: helvetica, arial;
          }
          h1 {
            text-align:center;
            position:relative;
          }
          .page {
            width: 80%;
            max-width: 500px;
            margin: auto;
            margin-top: 40px;
            margin-bottom: 40px;
            padding: 80px;
            background: #FCF6FC;
            border: 1px solid #eee;
            box-shadow: 0 10px 6px -6px #797;
          }
          ul {
            border-top: 1px dotted #ccc;
            padding: 10px 0 0 0;
            -webkit-padding-start: 0;
          }
          li {
            padding-top: 10px;
          }
          a,
          a:visited {
            text-decoration: underline;
            color: #555;
          }
          a:active,
          a:hover {
            color: #222;
          }
          p {
            text-indent: 1em;
          }
        </style>
      </body>
    </html>`
    
    

    这其中有一个坑需要注意的是,就是go get github.com/gophercises/cyoa后,会报错

    package github.com/gophercises/cyoa: no Go files in /Users/mac/go/src/github.com/gophercises/cyoa

    go在下载第三方包的时候,会在下载到我的go的路径下,比如我的电脑的根目录就是/Users/mac,第三方包会放到 ~/go/src/github.com/,github的项目会下载到这个地址。上面的那个错,是因为没有把github中的story.go 那个文件下载下来,这时我是直接去项目中下载到我的电脑,然后又放入我的根目录的。

    参考链接

    https://github.com/gophercises/cyoa/tree/solution

    相关文章

      网友评论

          本文标题:Go小项目-新闻网站

          本文链接:https://www.haomeiwen.com/subject/urpfqftx.html