简体   繁体   English

在测试golang中终止正在运行的进程

[英]kill running process in test golang

Writing a program based on http.ListenAndServe and writing the tests i've hit a stump. 编写基于http.ListenAndServe的程序并编写测试,我遇到了http.ListenAndServe my test looks like this 我的测试看起来像这样

package main

import (
    "testing"
    "../"
)

func TestServer(t *testing.T) {
    Server.Server()
}

and the tested function 和经过测试的功能

package Server

import (
    "net/http"
)

var (
    DefaultPort = "8080"
    DefaultDir = "."
)

func Server() {
    port := DefaultPort
    directory := DefaultPort

    http.ListenAndServe(":"+port, http.FileServer(http.Dir(directory)))
}

my goal is to be able to run test and after the server listener is launched kill it and return a success message 我的目标是能够运行测试,并在启动服务器侦听器后将其杀死并返回成功消息

You can't. 你不能 To be able to stop, you need to create Listener by hand 为了能够停止,您需要手动创建侦听器

listener, err := net.Listen("http", ":"+port)
err=http.Serve(listener, http.FileServer(http.Dir(directory)))

then you can 那么你也能

err=listener.Close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM