In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "how to configure HTTP Server in swoft2". In daily operation, I believe many people have doubts about how to configure HTTP Server in swoft2. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "how to configure HTTP Server in swoft2"! Next, please follow the editor to study!
Configuration parameters
In the app/bean.php configuration server under the application, in this file, you can see that the Http Server array contains the basic information of Http Server. Here are some simple configurations, and you can freely combine and provide multiple services at the same time.
'httpServer' = > [' class' = > HttpServer::class, 'port' = > 18306,' listener' = > ['rpc' = > bean (' rpcServer')], 'process' = > [/ /' monitor' = > bean (MonitorProcess::class) / / 'crontab' = > bean (CrontabProcess::class)],' on' = > [/ / Enable task must task and finish event SwooleEvent::TASK = > bean (TaskListener::class), SwooleEvent::FINISH = > bean (FinishListener::class)] / * @ see HttpServer::$setting * / 'setting' = > [' task_worker_num' = > 12, 'task_enable_coroutine' = > true,' worker_num' = > 6, / / Enable Https this can be configured with https certificate without setting 'ssl_cert_file' = >' / my/certs/2288803_www.domain.com.pem', 'ssl_key_file' = >' / my/certs/2288803_www.domain.com.key',]] / / Enable Https' type' = > SWOOLE_SOCK_TCP | SWOOLE_SSL
The configuration item http server is a property of http server except class.
Configuration introduction
Class specifies the processing class for Http Server
Port specifies the port of the Http Server
Listener specifies other services that are started together. You can add multiple port service listeners.
Rpc starts the RPC service
Process starts a custom user process
On configuration listens for events to register events, sets corresponding event handling listeners, events trigger component calls, and use in tasks
Setting here is the reference Swoole Server configuration option
PidFile sets the process pid file location. The default is @ runtime/swoft.pid.
For the mode in which mode runs, refer to the third argument of the Swoole Server constructor
Type specifies the type of Socket and supports the fourth parameter of the Swoole Server constructor, such as TCP, UDP, TCP6, UDP6, UnixSocket Stream/Dgram, etc.
Enable Https support Note: you must install the OpenSSL library and make sure that the ssl option is enabled when installing swoole. At the same time, set 'type' = > SWOOLE_SOCK_TCP | SWOOLE_SSL
Controller controller
As the core component of HTTP service, the controller concatenates the whole life cycle of a request. Through annotations, compared with the traditional Controller, the code is more concise, and users can pay more attention to business logic.
Create a controller
This is mainly achieved through the @ Controller annotation. The code can be placed anywhere, but for a uniform standard, it is recommended to put it under app/Http/Controller
Namespace App\ Http\ Controller;use Swoft\ Http\ Message\ ContentType;use Swoft\ Http\ Message\ Response;use Swoft\ Http\ Server\ Annotation\ Mapping\ Controller;use Swoft\ Http\ Server\ Annotation\ Mapping\ RequestMapping;use Swoft\ View\ Annotation\ Mapping\ View;use Throwable / * Class ViewController * * @ since 2.0 * * @ Controller (prefix= "view") * / class ViewController {/ * * @ RequestMapping ("index") * * @ param Response $response * * @ return Response * / public function index (Response $response): Response {$response = $response- > withContent ('Swoft framework'); $response = $response- > withContentType (ContentType::HTML); return $response;}}
Code analysis
@ Controller comment
Http controller class annotation @ Controller
Annotation class: Swoft\ Http\ Server\ Annotation\ Mapping\ Controller
Scope of action: CLASS
Owning attributes:
Prefix specifies the routing prefix
Usually only @ Controller doesn't work, and it needs to work with the next @ RequestMapping to work correctly.
Routing rules
Explicitly specify the routing prefix: @ Controller (prefix= "/ index") or @ Controller ("/ index").
Implicitly specify the routing prefix: @ Controller () automatically resolves the name of controller class using the small hump format by default.
Example: class IndexController corresponds to route / index
A complete routing rule is implemented through @ Controller + @ RequestMapping annotations, usually the former defining prefixes and the latter defining suffixes. The @ RequestMapping comment will be routed later-the @ RequestMapping section will cover it in more detail.
In Swoft, it is wrong not to inherit the member properties of the parent controller in accordance with the traditional fpm framework for use in other controllers.
Error demonstration:
/ * * @ Controller () * / class BaseController {protected $num;} / * * @ Controller (prefix= "/ v1/index") * / class IndexController extends BaseController {/ * @ RequestMapping (route= "index") * / public function index () {$this- > num++; echo $this- > num. "\ n"; / / the output here is different each time.
At this time, the number of each visit to num will be increased by 1, which is the wrong way to use, which is very different from the traditional php-fpm. Traditional fpm releases memory after each execution, but swoft is resident in memory. We must pay attention to it.
Routin
Unlike the traditional PHP framework, Swoft does not use a configuration file to configure routing, but uses annotations. In Swoft, we can use the @ RequestMapping annotation to quickly add routes.
@ RequestMapping comment
Http Controller Class Chinese French routing Note @ RequestMapping
Route routing Rule path
Method request method (GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD)
Params can use it to add regular matching restrictions to path variables
Try to write only one @ RequestMapping annotation for each method to avoid confusion.
Routing rules
Typically, a complete route path equals @ Controller prefix + @ RequestMapping route displays the specified route suffix: @ RequestMapping ("index") or @ RequestMapping (route= "index")
Implicitly specify a routing suffix: use the @ RequestMapping () default parsing method named suffix
Specifically, when your @ RequestMapping route begins with /, the complete route is it, that is, prefix will no longer be added in front of it
The allowed request methods are GET and POST by default. When setting cross-domain, you need to manually specify allow OPTIONS.
Bind routing path parameter
Specify the routing parameter: @ RequestMapping (route= "index/ {name}"). You can directly use $name as the method parameter in the Action method.
URL path pass parameters are optional when routing parameters are wrapped in []. Note that optional characters can only be used at the end
Example 1: @ RequestMapping ("/ index [/ {name}]") so that / index/ index/tom can access the
Example 2: @ RequestMapping ("/ about [.html]") is equivalent to pseudo-static, which can be accessed by / about / about.html
Set the routing request mode
If you want to set the HTTP request method that allows the request controller. You can configure method parameters using the @ RequestMapping annotation in the controller using the method, which can be one or more of GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.
RequestMapping (route= "index", method= {RequestMethod::GET,RequestMethod::POST})
Please remember to introduce the relevant annotation classes
Swoft\ Http\ Server\ Annotation\ Mapping\ RequestMappingSwoft\ Http\ Server\ Annotation\ Mapping\ RequestMethod
Http request object
The request and response of Swoft is implemented in the PSR-7 specification. Request and response objects exist in each HTTP request.
The request object Request is Swoft\ Http\ Message\ Request
The response object Response is Swoft\ Http\ Message\ Response
Get the request object
$request = context ()-> getRequest ()
Example: get the requested URI
$uri=$request- > getUri ()
The URI of the request object is itself an object, which provides the following methods to check the URL portion of the HTTP request
$uri- > getScheme () $uri- > getAuthority () $uri- > getUserInfo () $uri- > getHost () $uri- > getPort () $uri- > getPath () $uri- > getQuery () (for example, a=1&b=2) $uri- > getFragment ()
Example: get request Headers
All Headers
$headers = $request- > getHeaders ()
Specified Header
$host = $request- > getHeaderLine ("host")
Example: get the requested data
GET data
$data = $request- > query (); $some = $request- > query ('key','default value') $data = $request- > get (); $some = $request- > get (' key','default value')
POST data
$data = $request- > post (); $some = $request- > post ('key',' default value')
Regardless of the data format of the request, the json xml request is automatically parsed into php array data. Can be obtained through $request- > post ().
Simultaneously obtain GET & POST data
$data = $request- > input (); $some = $request- > input ('key',' default value')
RAW data
$data = $request- > raw ()
SERVER data
$data = $request- > getServerParams (); $some = $request- > server ('key',' default value')
Get uploaded files
$file = $request- > getUploadedFiles ()
The result is an one-dimensional array or a two-digit array, and the data structure is as follows. If a single file is uploaded in the form, an one-dimensional array is returned. The contents of the array are Swoft\ Http\ Message\ Upload\ UploadedFile file objects. For example, if the file field is named file, the data structure is as follows
Note that the properties of this UploadedFile object are private. Withdata filters private attributes, so output $file this object outputs an empty array instead of uploading unreceived data.
The result is an one-dimensional array or a two-digit array, and the data structure is as follows. If a single file is uploaded in the form, an one-dimensional array is returned. The contents of the array are Swoft\ Http\ Message\ Upload\ UploadedFile file objects. For example, if the file field is named file, the data structure is as follows
Array (1) {["file"] = > object (Swoft\ Http\ Message\ Upload\ UploadedFile) # 6510 (7) {["size": "Swoft\ Http\ Message\ Upload\ UploadedFile": private] = > int (1319) ["errorCode": "Swoft\ Http\ Message\ Upload\ UploadedFile": private] = > int (0) ["file": "Swoft\ Http\ Message\ Upload\ UploadedFile": private] = > string (25) "/ tmp/swoole.upfile.f7p2EL" [ "clientFilename": "Swoft\ Http\ Message\ Upload\ UploadedFile": private] = > string (6) "at.png" ["clientMediaType": "Swoft\ Http\ Message\ Upload\ UploadedFile": private] = > string (9) "image/png" ["moved": "Swoft\ Http\ Message\ Upload\ UploadedFile": private] = > NULL ["path": "Swoft\ Http\ Message\ Upload\ UploadedFile": private] = > NULL}}
If there is an array of fields in the form to upload multiple files such as file [], a two-dimensional array is returned, and the contents of the array are still Swoft\ Http\ Message\ Upload\ UploadedFile file objects, with the following data structure
Array (1) {[file "] = > array (2) {[0] = > object (Swoft\ Http\ Message\ Upload\ UploadedFile) # 6516 (7) {[" size ":" Swoft\ Http\ Message\ Upload\ UploadedFile ": private] = > int (1319) [" errorCode ":" Swoft\ Http\ Message\ Upload\ UploadedFile ": private] = > int (0) [" file ":" Swoft\ Http\ Message\ Upload\ UploadedFile ": private] = > string (25)" / tmp/swoole.upfile.TVKdOS "[" clientFilename ":" Swoft\ Http\ Message\ Upload\ UploadedFile ": private] = > string (6)" at.png "[" clientMediaType ":" Swoft\ Http\ Message\ Upload\ UploadedFile ": private] = > string (9)" image/png "[" moved ":" Swoft\ Http\ Message\ Upload\ UploadedFile ": private] = > NULL [path": "Swoft\ Http\ Message\ Upload\ UploadedFile": private] = > NULL}.}}
File operation method
MoveTo () moves the uploaded file to a new location.
GetSize () gets the file size in byte.
GetError () gets the error information related to the uploaded file. If there is no error, it must return the UPLOAD_ERR_OK constant, and if there is another error, it will return the UPLOAD_ERR_XXX-related constant.
GetClientFilename () gets the file name local to the client when the file is uploaded, and do not trust the value returned by this method. The client may send a malicious false file name in an attempt to destroy or crack your application.
GetClientMediaType () gets the MediaType type of the file in the client, and don't trust the value returned by this method. The client may send a malicious false file name in an attempt to destroy or crack your application.
Other commonly used auxiliary methods
If ($request- > isAjax ()) {/ / Do something} if ($request- > isGet ()) {/ / Do something} if ($request- > isPost ()) {/ / Do something}
Http response object
According to the immutability (immutable) of the PSR-7 object, all with* methods clone the object and return, must receive a new object for further processing, or use chained calls
For example:
Return $response- > withContentType (ContentType::HTML)-> withContent ('Swoft framework')
Get response object
$response=context ()-> getResponse ()
Set response status code
Return $response- > withStatus
Example: output string content response
Return $response- > withContent ("Hello Swoft2.0")
Example: output array content response
$data = ['name'= >' Swoft2.0']; return $response- > withData ($data)
Example: set response header information
Return $response- > withHeader ("name", "Swoft2.0")
Example: redirect
/ / 302return $response- > redirect ("http://www.swoft.org",302);// 404 pagereturn $response- > redirect ('/ 404')
Example: file download
Return $response- > file (\ alias ('@ runtime/1.zip'), "application/octet-stream")
Example: set Cookies
$response = $response- > withCookie ('name',' value'); $response = $response- > withCookie ('name', [' value' = > 'value3',' httpOnly' = > true]); Source: https://8code.net/index/index/article/id/47 so far, the study on "how to configure HTTP Server in swoft2" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.