随笔 - 272  文章 - 0  评论 - 283  阅读 - 142万

Go语言实现http共享

在我之前的文章(http://www.cnblogs.com/MikeZhang/archive/2012/02/11/httpFileSharePythonAndGo.html)中提到过用go语言实现http共享,这个程序我一直在用,感觉还是python的方式更加灵活:如不指定端口,则默认开启8000……

python不给力,慢不说,还只允许一个客户端,果断决定自己写一个!

好了,不多废话了,代码如下:

 /*

File      : httpShare.go
Author    : Mike
E-Mail    : Mike_Zhang@live.com
*/
package main
import (
        "net/http"
        "os"
        "strings"
)
func shareDir(dirName string,port string,ch chan bool){
        h := http.FileServer(http.Dir(dirName))
        err := http.ListenAndServe(":"+port,h)
        if err != nil {
                println("ListenAndServe : ",err.Error())
                ch <- false
        }
}
func main(){
        ch := make(chanbool)
        port := "8000"//Default port 
        iflen(os.Args)>1 {
                port = strings.Join(os.Args[1:2],"")
        }
        go shareDir(".",port,ch)
        println("Listening on port ",port,"...")
        bresult := <-ch
        iffalse == bresult {
                println("Listening on port ",port," failed")
        }
}

运行效果如下:

1、正常情况下:

2、端口被占用时:

好,就这些来,希望对你有帮助。

posted on   Mike_Zhang  阅读(3080)  评论(3编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2012年3月 >
26 27 28 29 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
1 2 3 4 5 6 7

点击右上角即可分享
微信分享提示