golang Windows环境下 http设置静态目录

网上查看 https://www.ctolib.com/topics-80226.html,等一众文章介绍http设置静态目录的路径,用的都是"/Users/chenjiebin/Sites/goexample/net/http/static",可能是Linux环境下的目录路径,亲测windows下相当路径的格式" 文件名/.." 不需要最前面加个"/"

用golang开发http服务的时候,有时会需要一个静态目录来存放css,js和image图片,并且能通过http访问到。在golang可以用http.FileServer来处理。



package main

import (

  "fmt"

  "html/template"

  "log"

  "net/http"

  //"strings"

)

func sayhelloword(w http.ResponseWriter, r *http.Request) {

  fmt.Println("sayhelloword")

  fmt.Fprintf(w, "Hello World by LJJ!") //这个写入到w的是输出到客户端的

}

func reactWebPage(w http.ResponseWriter, r *http.Request) {

  file := "staticBuild/index.html"

  t, _ := template.ParseFiles(file)

  t.Execute(w, "Hello world")

}

func main() {

  http.HandleFunc("/helloword", sayhelloword) //设置访问的路由  进入路由/helloword后,先调用sayhelloword,还会调用sayhelloName可能是因为“/”

  http.HandleFunc("/reactWebPage", reactWebPage)

  // 设置静态目录

  fsh := http.FileServer(http.Dir("staticBuild/static"))

  http.Handle("/static/", http.StripPrefix("/static/", fsh))

  err := http.ListenAndServe(":9090", nil) //设置监听的端口

  if err != nil {

    log.Fatal("ListenAndServe: ", err)

  }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • golang http http 挂载方法 Head 发送 HEAD 请求func Head(url string...
    copyLeft阅读 647评论 0 0
  • 一、数据类型转换 https://studygolang.com/articles/10838 package m...
    蓓蓓的万能男友阅读 1,111评论 0 1
  • 前言: golang处理http一般有这几种方式: 直接使用net包(这个是很底层的包,...
    coopbee阅读 2,992评论 0 3
  • 转发自:http://shanshanpt.github.io/2016/05/03/go-gin.html gi...
    dncmn阅读 6,099评论 0 1
  • 最近起的比较早,五点多醒一次不会立马睡,玩一会儿之后睡个回笼觉,大概在七点左右醒来。半夜咳嗽一次(两声),天亮在翻...
    山城季阅读 228评论 0 0